<template>
	<view class="login-container">
		<view class="content">
			<view class="login-panel">
				<text class="login-title">用户登录</text>

				<!-- 登录身份选择 -->
				<view class="form-group">
					<text class="form-label">登录身份</text>
					<picker @change="roleChange" :value="roleIndex" :range="roles" class="role-select">
						<view class="picker-text">{{roles[roleIndex]}}</view>
					</picker>
				</view>

				<!-- 手机号码输入 -->
				<view class="form-group">
					<text class="form-label">手机号码</text>
					<input type="number" v-model="phoneNumber" placeholder="请输入手机号码" maxlength="11" class="input" />
				</view>

				<!-- 验证码 -->
				<view class="form-group verification-group">
					<text class="form-label">验证码</text>
					<view class="verification-input-group">
						<input type="number" v-model="inputVerificationCode" placeholder="请输入验证码" maxlength="4" class="input" />
						<view class="verification-code" @tap="refreshVerificationCode">
							{{ verificationCode }}
						</view>
					</view>
				</view>

				<!-- 错误信息 -->
				<view class="error-message" v-if="loginError">
					{{ loginError }}
				</view>

				<!-- 登录按钮 -->
				<button class="login-btn" @tap="validateLogin">登录</button>

				<!-- 登录页脚 -->
				<view class="login-footer">
					<text>登录即表示您同意我们的</text>
					<text class="link-text">服务条款</text>
					<text>和</text>
					<text class="link-text">隐私政策</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	// // 确保路径正确
	
	import { getUserByPhone } from '@/js/user.js'
	import { getDoctorByPhone, updateDoctor } from '@/js/doctor.js'
	import { setToken } from '../../utils/auth.js'
	
	export default {
		data() {
			return {
				phoneNumber: '',
				inputVerificationCode: '',
				verificationCode: '',
				loginError: '',
				roles: ['患者', '医生'],
				roleIndex: 0,
				selectedRole: 'patient' // 默认患者
			}
		},
		onLoad() {
			this.generateVerificationCode();
		},
		methods: {
			// 生成随机验证码
			generateVerificationCode() {
				this.verificationCode = Math.floor(1000 + Math.random() * 9000).toString();
			},
			
			// 刷新验证码
			refreshVerificationCode() {
				this.generateVerificationCode();
			},
			
			// 角色选择变化
			roleChange(e) {
				this.roleIndex = e.detail.value;
				this.selectedRole = this.roleIndex === 0 ? 'patient' : 'doctor';
			},
			
			// 登录验证
			async validateLogin() {
				
				try {
					// 验证手机号
					if (!this.phoneNumber || this.phoneNumber.length !== 11) {
						this.loginError = '请输入正确的手机号码';
						return;
					}
					
					// 验证验证码
					if (this.inputVerificationCode !== this.verificationCode) {
						this.loginError = '验证码错误';
						return;
					}
					
					console.log('开始验证手机号:', this.phoneNumber);
					
					// 调用后端接口验证手机号是否存在
					// 根据角色选择接口
					let result;
					let apiResponse;
					if (this.selectedRole === 'patient') {
					    apiResponse = await getUserByPhone(this.phoneNumber);
					    result = apiResponse;  // 保留完整的响应
					} else {
					    result = await getDoctorByPhone(this.phoneNumber);
					}

					if (result.code == 0) {
					    if (result.data != null) {
					        // 根据角色存储信息
					        if (this.selectedRole === 'patient') {
					            uni.setStorageSync('userInfo', JSON.stringify(result.data));
					            uni.removeStorageSync('doctorInfo');
					        } else {
								// 如果是医生登录，更新状态为"值班"
								const doctorData = result.data;
								uni.setStorageSync('doctorInfo', JSON.stringify(doctorData));
								uni.removeStorageSync('userInfo');
								
								// 更新医生状态为"值班"
								try {
									await updateDoctor({
										...doctorData,
										status: '值班'
									});
									console.log('医生状态已更新为值班');
								} catch (updateError) {
									console.error('更新医生状态失败:', updateError);
									// 继续登录流程，不阻止用户登录
								}
							}
							
							// 根据角色跳转到不同页面
							if (this.selectedRole === 'patient') {
								uni.navigateTo({
									url: '/pages/patient/patient'
								});
							} else {
								uni.navigateTo({
									url: '/pages/doctor/doctor'
								});
							}
						} else {
							// 用户不存在的处理
							if (this.selectedRole === 'patient') {
								// 患者不存在，跳转到个人中心页面进行注册
								console.log('用户不存在，进行注册');
								uni.setStorageSync('tempPhone', this.phoneNumber);
								uni.setStorageSync('needRegister', 'true');
								uni.navigateTo({
									url: '/pages/personal/index'
								});
							} else {
								// 医生不存在，显示错误信息
								throw new Error('该手机号未注册医生账号');
							}
						}
					} else {
						// 接口返回错误
						throw new Error('接口出错，请稍后再试');
					}
				} catch (error) {
					console.error('登录失败:', error);
					this.loginError = error.message || '登录失败，请稍后再试';
				}
			}
		}
	}
</script>

<style>
	.login-container {
		width: 100%;
		height: 100vh;
		background-color: #f8f8f8;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.content {
		width: 90%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0;
		margin-top: 60rpx;
	}
	
	.login-panel {
		width: 100%;
		background-color: #ffffff;
		border-radius: 20rpx;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
		padding: 40rpx;
	}
	
	.login-title {
		font-size: 48rpx;
		color: #8B4513;
		text-align: center;
		margin-bottom: 60rpx;
	}
	
	.form-group {
		margin-bottom: 40rpx;
	}
	
	.form-label {
		display: block;
		font-size: 32rpx;
		color: #5D4037;
		margin-bottom: 16rpx;
	}
	
	.input {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #d1c4b0;
		border-radius: 10rpx;
		font-size: 28rpx;
		color: #333;
		background-color: #ffffff;
		padding: 0 20rpx;
	}
	
	.role-select {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #d1c4b0;
		border-radius: 10rpx;
		background-color: #ffffff;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
	}
	
	.picker-text {
		font-size: 28rpx;
		color: #333;
	}
	
	.verification-input-group {
		display: flex;
		flex-direction: row;
	}
	
	.verification-input-group .input {
		flex: 1;
	}
	
	.verification-code {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 200rpx;
		height: 80rpx;
		background-color: #f0e6d2;
		border: 1rpx solid #d1c4b0;
		border-radius: 10rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: #8B4513;
		margin-left: 20rpx;
	}
	
	.error-message {
		color: #d9534f;
		font-size: 24rpx;
		margin-bottom: 30rpx;
		text-align: center;
	}
	
	.login-btn {
		width: 100%;
		height: 80rpx;
		background-color: #8B4513;
		color: white;
		border: none;
		border-radius: 10rpx;
		font-size: 32rpx;
		margin-bottom: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.login-footer {
		margin-top: 40rpx;
		text-align: center;
		font-size: 24rpx;
		color: #666;
		display: flex;
		justify-content: center;
		flex-wrap: wrap;
	}
	
	.link-text {
		color: #8B4513;
		margin: 0 4rpx;
	}
</style>